﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EPiServer.PlugIn;
using EPiServer.Licensing;
using Auros.EPiSiteMap.Data;
using Auros.EPiSiteMap.WebControls;

namespace Auros.EPiSiteMap
{
    [GuiPlugIn(
        DisplayName = "Sitemap Management", 
        Description="Configure the xml sitemaps which should be generated for a site",
        Area = PlugInArea.AdminMenu,
        RequiredAccess = EPiServer.Security.AccessLevel.Administer,
        Url = "~/Modules/Sitemap/Admin.aspx")]
    public partial class Admin : EPiServer.UI.SystemPageBase
    {
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            this.MasterPageFile = ResolveUrlFromUI("MasterPages/EPiServerUI.master");
            this.SystemMessageContainer.Heading = "Sitemap Management";
        } 
        
        protected void Page_Load(object sender, EventArgs e)
        {
            SitesRepeater.DataSource = SiteInformationHandler.GetSitesInformation(true);
            SitesRepeater.DataBind();

            if (!Page.IsPostBack)
            {
                var config = SiteMapConfig.GetConfig();

                this.SiteMapIndexRequired.Checked = config.CreateIndexFile;
                this.SiteMapIndexFileName.Text = config.SitemapIndexFileName;
            }
        }

        protected void SaveButtonClick(object sender, EventArgs e)
        {
            // Enumerate each table and its rows to save into DDS
            for (int i = 0; i < this.SitesRepeater.Items.Count; i++)
            {
                SiteMapTable table = this.SitesRepeater.Items[i].FindControl("SiteHostsTable") as SiteMapTable;

                if (table != null)
                {
                    table.Save();
                }
            }

            var config = SiteMapConfig.GetConfig();

            config.CreateIndexFile = this.SiteMapIndexRequired.Checked;
            config.SitemapIndexFileName = this.SiteMapIndexFileName.Text;

            SiteMapConfig.SaveConfig(config);

            this.SystemMessageContainer.Message = "Configuration Saved.";
        }
    }
}